import { memo, useEffect, useState } from 'react';
import { useSidebarActions, useFileOperations } from '../../stores';
import FileTree from './FileTree';
import { Dialog, Button, Input } from '../common';
import { FaFolder, FaRegFile, FaFolderPlus, FaChevronLeft, FaChevronRight } from 'react-icons/fa6';
import styles from './Sidebar.module.css';

const Sidebar = memo(() => {
  const { 
    isOpen: isSidebarOpen, 
    toggleSidebar, 
    setSidebarOpen, 
    isMobileDevice 
  } = useSidebarActions();

  const { fileOperations } = useFileOperations();
  const [newFileDialog, setNewFileDialog] = useState({
    isOpen: false,
    fileName: ''
  });
  const [newFolderDialog, setNewFolderDialog] = useState({
    isOpen: false,
    folderName: ''
  });

  const isMobile = isMobileDevice();

  // 监听窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      const mobile = isMobileDevice();
      // 如果切换到移动端且sidebar开启，则关闭它
      if (mobile && isSidebarOpen) {
        setSidebarOpen(false);
      }
    };

    window.addEventListener('resize', handleResize);
    
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [isSidebarOpen, setSidebarOpen, isMobileDevice]);

  const handleToggle = () => {
    toggleSidebar();
  };

  const handleBackdropClick = () => {
    // 移动端点击背景关闭sidebar
    if (isMobile && isSidebarOpen) {
      setSidebarOpen(false);
    }
  };

  const handleNewFile = () => {
    setNewFileDialog({ isOpen: true, fileName: '' });
  };

  const handleNewFolder = () => {
    setNewFolderDialog({ isOpen: true, folderName: '' });
  };

  const handleConfirmNewFile = async () => {
    if (newFileDialog.fileName.trim()) {
      const fileName = newFileDialog.fileName.trim();
      // 顶部按钮创建的文件都在根目录下
      const result = await fileOperations.createFile(fileName, '', 0);
      
      if (result.success) {
        console.log('文件创建成功:', fileName);
      } else {
        console.error('文件创建失败:', result.error);
      }
    }
    setNewFileDialog({ isOpen: false, fileName: '' });
  };

  const handleConfirmNewFolder = async () => {
    if (newFolderDialog.folderName.trim()) {
      const folderName = newFolderDialog.folderName.trim();
      // 顶部按钮创建的文件夹都在根目录下
      const result = await fileOperations.createFolder(folderName, 0);
      
      if (result.success) {
        console.log('文件夹创建成功:', folderName);
      } else {
        console.error('文件夹创建失败:', result.error);
      }
    }
    setNewFolderDialog({ isOpen: false, folderName: '' });
  };

  return (
    <>
      {/* 移动端背景遮罩 */}
      {isMobile && isSidebarOpen && (
        <div 
          className={styles.backdrop}
          onClick={handleBackdropClick}
        />
      )}
      
      {/* Sidebar 容器 */}
      <div 
        className={`${styles.sidebar} ${isSidebarOpen ? styles.open : styles.closed} ${isMobile ? styles.mobile : styles.desktop}`}
      >
        {/* Sidebar 头部 */}
        <div className={styles.header}>
          <h2 className={styles.title}>
            <FaFolder className={styles.titleIcon} />
            <span className={styles.titleText}>文件浏览器</span>
          </h2>
          
          <div className={styles.headerActions}>
            <button
              className={styles.newFileButton}
              onClick={handleNewFile}
              title="新建文件"
            >
              <FaRegFile />
            </button>
            
            <button
              className={styles.newFolderButton}
              onClick={handleNewFolder}
              title="新建文件夹"
            >
              <FaFolderPlus />
            </button>
            
            <button
              className={styles.toggleButton}
              onClick={handleToggle}
              title={isSidebarOpen ? '收起侧边栏' : '展开侧边栏'}
            >
              {isSidebarOpen ? <FaChevronLeft className={styles.toggleIcon} /> : <FaChevronRight className={styles.toggleIcon} />}
            </button>
          </div>
        </div>

        {/* Sidebar 内容 */}
        <div className={styles.content}>
          <FileTree />
        </div>
        
        {/* 拖拽调整大小的手柄 (仅桌面端) */}
        {!isMobile && (
          <div 
            className={styles.resizeHandle}
          />
        )}
      </div>

      {/* 新建文件对话框 */}
      <Dialog
        isOpen={newFileDialog.isOpen}
        onClose={() => setNewFileDialog({ isOpen: false, fileName: '' })}
        title="新建文件"
        size="small"
        footer={
          <>
            <Button
              variant="secondary"
              onClick={() => setNewFileDialog({ isOpen: false, fileName: '' })}
            >
              取消
            </Button>
            <Button
              variant="primary"
              onClick={handleConfirmNewFile}
              disabled={!newFileDialog.fileName.trim()}
            >
              创建
            </Button>
          </>
        }
      >
        <Input
          value={newFileDialog.fileName}
          onChange={(e) => setNewFileDialog({ ...newFileDialog, fileName: e.target.value })}
          placeholder="输入文件名 (例如: main.py)"
          label="文件名"
          autoFocus
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              handleConfirmNewFile();
            }
          }}
        />
      </Dialog>

      {/* 新建文件夹对话框 */}
      <Dialog
        isOpen={newFolderDialog.isOpen}
        onClose={() => setNewFolderDialog({ isOpen: false, folderName: '' })}
        title="新建文件夹"
        size="small"
        footer={
          <>
            <Button
              variant="secondary"
              onClick={() => setNewFolderDialog({ isOpen: false, folderName: '' })}
            >
              取消
            </Button>
            <Button
              variant="primary"
              onClick={handleConfirmNewFolder}
              disabled={!newFolderDialog.folderName.trim()}
            >
              创建
            </Button>
          </>
        }
      >
        <Input
          value={newFolderDialog.folderName}
          onChange={(e) => setNewFolderDialog({ ...newFolderDialog, folderName: e.target.value })}
          placeholder="输入文件夹名称"
          label="文件夹名称"
          autoFocus
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              handleConfirmNewFolder();
            }
          }}
        />
      </Dialog>
    </>
  );
});

Sidebar.displayName = 'Sidebar';

export default Sidebar;
